#include <stdlib.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <avr/pgmspace.h>
#include "uart.h"
#include "lcd.h"
//#include "adc.h"

/* 9600 baud */
#define UART_BAUD_RATE      9600
#define xtalCpu 7372800L
char *mobile="+918800943322";
char str[20],string[20];
int i=0,call=1,cmd=0,status=0,signal=0;
uint16_t buffer;
void chk_str(unsigned char c){
str[i]=c;
call=0;
uart_putc(str[i]);
	if(str[i]==13)
	{++status;}
	if(status>=2)
	{
	//uart_putc(str[i]);
		//if(str[i]=='O')
		//{uart_putc('\n');
		//uart_putc('O');}
		if(cmd==3)
		{
			if(str[i]==10)
			{
			//uart_putc('d');
			status=0;
			call=1;
			cmd++;
			poke_modem(mobile);
			}
		}
		if(str[i]=='K')
		{//uart_putc('K');
		 status=0;
		 call=1;
		 cmd++;
		 poke_modem(mobile);
		 }
	}
i=i++;
}

void poke_modem(char *mobile_num){
if(call==1)
{
	if(cmd==0){
	uart1_puts("AT\r\n");}
	
	if(cmd==1){
	uart1_puts("AT+CMGF=1\r\n");}
	
	if(cmd==2){
	uart1_puts("AT+CSCS=");
	uart1_putc(34);
	uart1_puts("GSM");
	uart1_putc(34);
	uart1_puts("\r");
	//uart1_puts(10);
	}
	
	if(cmd==3){
	uart1_puts("AT+CMGS=");
	uart1_putc(34);
	uart1_puts(mobile_num);
	uart1_putc(34);
	uart1_puts("\r");
	}
	
	if(cmd==4){
	uart1_puts("Over Voltage at SW1");
	//uart1_puts("TURN OFF NOW");
	uart1_puts("\r");
	uart1_putc(26);
	}
}
}
void InitADC()
{
 // Select Vref=AVcc
 ADMUX |= (1<<REFS0);
 //set prescaller to 128 and enable ADC 
 ADCSRA |= (1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0)|(1<<ADEN);    
 }

uint16_t ReadADC(uint8_t ADCchannel)
{
 //select ADC channel with safety mask
 ADMUX = (ADMUX & 0xF0) | (ADCchannel & 0x0F);
 //single conversion mode
 ADCSRA |= (1<<ADSC);
 // wait until ADC conversion is complete
 while( ADCSRA & (1<<ADSC) );
 return ADC;
}

int main(){

uart1_init( UART_BAUD_SELECT(UART_BAUD_RATE,F_CPU) );
uart_init( UART_BAUD_SELECT(UART_BAUD_RATE,F_CPU) );
lcd_init(LCD_DISP_ON); // Initialize LCD
InitADC(); //Initialize ADC

lcd_puts("GSM Based Fault Notification system");
_delay_ms(5000);		
sei();
while(1)
{
	lcd_clrscr();
	buffer=ReadADC(0);
	itoa(buffer,string,10);   // Convert int i to buffer string 
	lcd_puts("Current ADC Value is");
	lcd_gotoxy(5,1);
	lcd_puts(string);
	_delay_ms(100);
	if(buffer>1000&&signal==1)
	{//lcd_puts("Voltage Overload");
	uart_puts("Voltage Overload");
	_delay_ms(20);
	poke_modem(mobile);
	signal=0;
	}
	if(buffer<1000)
	{signal=1;}
	
}
	
//return 0;
}
